package cn.bytengine.stem.contexts;

import cn.hutool.core.lang.Assert;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 基础上下文实现，上下文Map支持并发，不支持扩展和父级上下文。
 */
class InternalCoreContext implements Context {
    private Map<String, Object> map;

    InternalCoreContext() {
        map = new ConcurrentHashMap<>();
    }

    InternalCoreContext(Map<String, Object> data) {
        map = new ConcurrentHashMap<>(data);
    }

    @Override
    public Object get(String key) {
        Assert.notNull(key, "The key is null.");
        return this.map.get(key);
    }

    @Override
    public Context set(String key, Object value) {
        Assert.notNull(key, "The key is null.");
        if (value != null) {
            this.map.put(key, value);
        } else {
            this.map.remove(key);
        }
        return this;
    }

    @Override
    public Context set(Map<String, Object> data) {
        this.map.putAll(data);
        return this;
    }

    @Override
    public boolean has(String key) {
        Assert.notNull(key, "The key is null.");
        return this.map.containsKey(key);
    }

    @Override
    public Context remove(String key) {
        Assert.notNull(key, "The key is null.");
        this.map.remove(key);
        return this;
    }

    @Override
    public Context parent() {
        return null;
    }

    @Override
    public boolean hasParent() {
        return false;
    }
}
